package com.magicalcoder.youyamvc.web.controller.web.student;
import com.magicalcoder.youyamvc.app.student.service.StudentService;
import com.magicalcoder.youyamvc.app.student.service.StudentProxyService;
import com.magicalcoder.youyamvc.app.student.constant.StudentConstant;
import com.magicalcoder.youyamvc.app.student.util.StudentUtil;
import com.magicalcoder.youyamvc.web.controller.web.student.param.StudentRequest;
import com.magicalcoder.youyamvc.web.controller.web.student.param.StudentResponse;
import com.magicalcoder.youyamvc.app.model.Student;
import com.magicalcoder.youyamvc.core.common.utils.ProjectUtil;
import com.magicalcoder.youyamvc.core.common.utils.MapUtil;
import com.magicalcoder.youyamvc.core.common.utils.ListUtils;
import com.magicalcoder.youyamvc.core.common.utils.StringUtils;
import com.magicalcoder.youyamvc.core.common.dto.AjaxData;
import com.magicalcoder.youyamvc.core.common.utils.copy.Copyer;
import com.magicalcoder.youyamvc.core.spring.admin.AdminLoginController;
import com.magicalcoder.youyamvc.core.spring.web.WebLoginController;
import com.magicalcoder.youyamvc.web.common.BaseController;
import com.magicalcoder.youyamvc.app.userweb.util.UserWebUtil;
import com.magicalcoder.youyamvc.core.common.exception.BusinessException;

import org.springframework.format.annotation.DateTimeFormat;
import java.util.*;
import java.math.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestMethod;

/**
* 代码为自动生成 Created by www.magicalcoder.com
* 如果你改变了此类 read 请将此行删除
* 欢迎加入官方QQ群:323237052
*/

@RequestMapping({"/user/student"})
@Controller
public class StudentUserController extends WebLoginController
{

    @Resource
    private StudentService studentService;
    @Resource
    private StudentProxyService studentProxyService;
    /** method:GET
    *   url:/user/student/list/{pageIndex}/{pageSize}?...
    *   demo:/user/student/list/1/20
    *   获取学生分页数据
    *   是否需要登录                          是
    *是否必须   入参                          注释
    *  是   @pageIndex                     (Integer)当前页码 [1,n]
    *  是   @pageSize                      (Integer)每页条数 [1,n]
    *  否   @callback                      (String)回调方法
    *  否   @orderBySqlField               (String)排序字段
    *  否   @descAsc                       (String)desc|asc
    *  否   @encode                        (String)编码 默认UTF-8
    *  否   @name                     (String)学生名称 
    *  否   @classId                     (Long)所属班级 
    *  否   @sex                     (Integer)性别 [{"":"全部"},{"0":"女"},{"1":"男"}]
    *  否   @id                     (Integer)主键 
    *  否   @adminUserId                     (Long)管理员 
    *  否   @createTime                     (Date)创建时间 
    *  否   @updateTime                     (Date)更新时间 
    *  否   @nameFirst                     (String)学生名称 
    *  否  in @classIdFirst                     (Long)所属班级 
    *  否  in @sexFirst                     (Integer)性别 [{"":"全部"},{"0":"女"},{"1":"男"}]
    *  否  in @adminUserIdFirst                     (Long)管理员 
    *  否  >= @updateTimeFirst                     (Date)更新时间 
    *  否  <= @updateTimeSecond                  (Date)更新时间 
    *  返回
    *   {
    *      code:0,message:"",jsonp:"",
    *      info:
                [{
    *              name         (String)学生名称 
    *              classId         (Long)所属班级 
    *              sex         (Integer)性别 [{"":"全部"},{"0":"女"},{"1":"男"}]
    *              id         (Integer)主键 
    *              adminUserId         (Long)管理员 
    *              createTime         (Date)创建时间 
    *              updateTime         (Date)更新时间 
    *      }]
    *   }
    */
    @RequestMapping(value={"list/{pageIndex}/{pageSize}"}, method={RequestMethod.GET})
    public void list(@PathVariable Integer pageIndex,@PathVariable Integer pageSize,
        @RequestParam(required=false, value="orderBySqlField") String orderBySqlField,
        @RequestParam(required=false, value="descAsc") String descAsc,
        @RequestParam(required=false, value="callback") String callback,
        @RequestParam(required=false, value="encode") String encode,
        @RequestParam(required = false,value ="name")   String name,
        @RequestParam(required = false,value ="classId")   Long classId,
        @RequestParam(required = false,value ="sex")   Integer sex,
        @RequestParam(required = false,value ="id")   Integer id,
        @RequestParam(required = false,value ="adminUserId")   Long adminUserId,
        @RequestParam(required = false,value ="createTime")      @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")Date createTime,
        @RequestParam(required = false,value ="updateTime")      @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")Date updateTime,
        @RequestParam(required = false,value ="nameFirst")                            String nameFirst ,
        @RequestParam(required = false,value ="classIdFirst")                            String classIdFirst ,
        @RequestParam(required = false,value ="sexFirst")                            String sexFirst ,
        @RequestParam(required = false,value ="adminUserIdFirst")                            String adminUserIdFirst ,
        @RequestParam(required = false,value ="updateTimeFirst")                    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")Date updateTimeFirst ,
        @RequestParam(required = false,value ="updateTimeSecond")                    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")Date updateTimeSecond ,
        HttpServletRequest request,HttpServletResponse response,ModelMap modelMap)
    {
        try{
            String orderBySqlFieldStr = ",name,class_id,sex,id,admin_user_id,create_time,update_time,";
            String orderBy = ProjectUtil.filterOrderBy(orderBySqlFieldStr,orderBySqlField,descAsc);
            if(StringUtils.isBlank(orderBy)){
                orderBy = "class_id desc";
            }
            pageSize = Math.min(StudentConstant.PAGE_MAX_SIZE,pageSize);
            int idx = (pageIndex.intValue() - 1) * pageSize;
            Long _userId = UserWebUtil.userId(request);
            Map<String,Object> query = MapUtil.buildMap("orderBy", orderBy,
         "name",name,
         "classId",classId,
         "sex",sex,
         "id",id,
         "adminUserId",adminUserId,
         "createTime",createTime,
         "updateTime",updateTime,
                    "nameFirst",nameFirst ,
                    "classIdFirst",ProjectUtil.toList(classIdFirst ,Long.class),
                    "sexFirst",ProjectUtil.toList(sexFirst ,Integer.class),
                    "adminUserIdFirst",ProjectUtil.toList(adminUserIdFirst ,Long.class),
                    "updateTimeFirst",updateTimeFirst ,
                    "updateTimeSecond",updateTimeSecond ,
                "start",idx,"limit", pageSize ,"userId",_userId);

            List<Student> pageList = this.studentService.getStudentList(query);
            toWebSuccessJson(callback,encode,response, coverToResponseList(pageList));
        }catch(Exception e){
            String exceptionMsg = ProjectUtil.buildExceptionMsg(e.getMessage());
            toWebExceptionJson(response,exceptionMsg);
        }
    }

    private List<StudentResponse> coverToResponseList(List<Student> pageList){
        if(ListUtils.isBlank(pageList)){
            return null;
        }
        return Copyer.copy(pageList,StudentResponse.class);
    }


    /** method:GET
    *   url:/user/student/item?...
    *   demo:/user/student/item
    *   获取学生详情数据
    *   是否需要登录                          是
    *是否必须   入参                          注释
    *  否   @callback                      (String)回调方法
    *  否   @encode                        (String)编码 默认UTF-8
     *  否  @id        (Integer) 主键
    *  返回
    *   {
    *      code:0,message:"",jsonp:"",
    *      info:
                {
    *              name         (String)学生名称 
    *              classId         (Long)所属班级 
    *              sex         (Integer)性别 [{"":"全部"},{"0":"女"},{"1":"男"}]
    *              id         (Integer)主键 
    *              adminUserId         (Long)管理员 
    *              createTime         (Date)创建时间 
    *              updateTime         (Date)更新时间 
    *      }
    *   }
    */
    @RequestMapping(value={"item"}, method={RequestMethod.GET})
    public void item(
        @RequestParam(required=false, value="callback") String callback,
        @RequestParam(required=false, value="encode") String encode,
        @RequestParam(required = false,value ="id")Integer id,
        HttpServletRequest request,HttpServletResponse response,ModelMap modelMap)
    {
        try{
            Long _userId = UserWebUtil.userId(request);
            Map<String,Object> query = MapUtil.buildMap(
                     "id",id,
                "userId",_userId
            );
            Student student = this.studentService.selectFirstStudent(query);
            toWebSuccessJson(callback,encode,response, Copyer.copy(student,new StudentResponse()));
        }catch(Exception e){
            String exceptionMsg = ProjectUtil.buildExceptionMsg(e.getMessage());
            toWebExceptionJson(response,exceptionMsg);
        }
    }

    /** method:post
    *   url:/user/student/save?...
    *   demo:/user/student/save?...
    *   保存学生
    *   是否需要登录               是
    *是否必须         入参         注释
    * 否name (String)学生名称  
    * 否classId (Long)所属班级  
    * 是sex (Integer)性别 [{"":"全部"},{"0":"女"},{"1":"男"}] 
    * 否id (Integer)主键  为空表示插入否则表示更新
    * 否adminUserId (Long)管理员  
    * 否createTime (Date)创建时间  
    * 否updateTime (Date)更新时间  
    *
    *   返回
    *   {
    *      code:0,message:"",jsonp:"",
    *      info:id 主键 Integer
    *   }
    */
    @RequestMapping(value={"save"}  ,method={RequestMethod.POST})
    public void save(@ModelAttribute StudentRequest studentRequest,

        @RequestParam(required=false, value="callback") String callback,
        @RequestParam(required=false, value="encode") String encode,
        HttpServletRequest request,HttpServletResponse response) {
        Long _userId = UserWebUtil.userId(request);
        try{
            Integer id = saveEntity(_userId,studentRequest);
            toWebSuccessJson(callback,encode,response, id);
        }catch (BusinessException e){
            String exceptionMsg = ProjectUtil.buildExceptionMsg(e.getMessage());
            toWebExceptionJson(callback,encode,response,e.getErrorCode(), exceptionMsg);
            e.printStackTrace();
        }
        catch (Exception e){
            String exceptionMsg = ProjectUtil.buildExceptionMsg(e.getMessage());
            toWebExceptionJson(callback,encode,response, exceptionMsg);
            e.printStackTrace();
        }
    }

    private Integer saveEntity(Long userId,StudentRequest studentRequest){
        if (studentRequest.getId() == null) {
            Student student = new Student();
            Copyer.copy(studentRequest,student);
            student.setCreateTime(new Date());
            return this.studentService.insertStudent(student);
        } else {
            Student entity = getEntity(userId,studentRequest.getId());
            if(entity!=null){
                Copyer.reflectCopyZeroNotNull(studentRequest, entity);
                entity.setUpdateTime(new Date());
                this.studentService.updateStudent(entity);
            }
        }
        return studentRequest.getId();
    }

    private Student getEntity(Long userId,Integer id){
        return this.studentService.selectOneStudentWillThrowException(ProjectUtil.buildMap(
            "id",id));
    }

    /** method:get
    *   url:/user/student/delete?...
    *   demo:/user/student/delete?...

    *   删除学生
    *   是否需要登录                          是
    *是否必须   入参                          注释
    *  否   @callback                      (String)回调方法
    *  否   @encode                        (String)编码 默认UTF-8
    *  否  @id        (Integer) 主键
    *   返回
    *   {
    *      code:0,message:"",jsonp:"",
    *      info:true||false
    *   }
    */
    @RequestMapping(value={"delete"}, method={RequestMethod.GET})
    public void delete(
        @RequestParam(required=false, value="callback") String callback,
        @RequestParam(required=false, value="encode") String encode,
        @RequestParam(required = false,value ="id")Integer id,
    HttpServletRequest request,HttpServletResponse response)
    {
        try{
            Long _userId = UserWebUtil.userId(request);
            Map<String,Object> query = MapUtil.buildMap(
            "id",id,
            "userId",_userId
            );
            this.studentService.deleteStudentList(query);
            toWebSuccessJson(callback,encode,response, true);
        }catch(Exception e){
            String exceptionMsg = ProjectUtil.buildExceptionMsg(e.getMessage());
            toWebExceptionJson(response,exceptionMsg);
        }
    }



}